import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:5197';

interface LoginRequest {
  username: string;
  password: string;
}

interface LoginResponse {
  token: string;
  userId: string;
  username: string;
}

interface RegisterRequest {
  username: string;
  password: string;
  email: string;
}

class AuthService {
  private token: string | null = null;

  constructor() {
    // 清理无效的localStorage数据
    this.cleanupInvalidData();
    
    // 从localStorage恢复token
    this.token = localStorage.getItem('authToken');
    if (this.token) {
      this.setAuthHeader(this.token);
    }
    
    // 设置axios拦截器处理401错误
    this.setupAxiosInterceptors();
  }

  private setAuthHeader(token: string) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  private removeAuthHeader() {
    delete axios.defaults.headers.common['Authorization'];
  }

  private setupAxiosInterceptors() {
    // 响应拦截器，处理401错误
    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          // Token无效或过期，自动登出
          this.logout();
          // 可以在这里触发重新登录的逻辑
          window.location.reload();
        }
        return Promise.reject(error);
      }
    );
  }

  async login(credentials: LoginRequest): Promise<LoginResponse> {
    try {
      const response = await axios.post(`${API_BASE_URL}/api/auth/login`, credentials);
      const { token, user } = response.data;
      
      this.token = token;
      localStorage.setItem('authToken', token);
      localStorage.setItem('userId', user.id);
      localStorage.setItem('username', user.username);
      
      this.setAuthHeader(token);
      
      return { token, userId: user.id, username: user.username };
    } catch (error: any) {
      console.error('登录失败:', error);
      throw new Error(error.response?.data?.message || '登录失败');
    }
  }

  async register(userData: RegisterRequest): Promise<void> {
    try {
      await axios.post(`${API_BASE_URL}/api/auth/register`, userData);
    } catch (error: any) {
      console.error('注册失败:', error);
      throw new Error(error.response?.data?.message || '注册失败');
    }
  }

  logout() {
    this.token = null;
    localStorage.removeItem('authToken');
    localStorage.removeItem('userId');
    localStorage.removeItem('username');
    this.removeAuthHeader();
  }

  // 清理无效的localStorage数据
  private cleanupInvalidData() {
    const username = localStorage.getItem('username');
    const userId = localStorage.getItem('userId');
    
    if (username === 'undefined') {
      localStorage.removeItem('username');
    }
    if (userId === 'undefined') {
      localStorage.removeItem('userId');
    }
  }

  isAuthenticated(): boolean {
    if (!this.token) {
      return false;
    }
    
    // 检查token是否过期
    try {
      const payload = JSON.parse(atob(this.token.split('.')[1]));
      const currentTime = Math.floor(Date.now() / 1000);
      
      if (payload.exp && payload.exp < currentTime) {
        // Token已过期，清理认证信息
        this.logout();
        return false;
      }
      
      return true;
    } catch (error) {
      // Token格式无效，清理认证信息
      this.logout();
      return false;
    }
  }

  getToken(): string | null {
    return this.token;
  }

  getUsername(): string | null {
    const username = localStorage.getItem('username');
    return username === 'undefined' || username === null ? null : username;
  }

  getUserId(): string | null {
    return localStorage.getItem('userId');
  }
}

export const authService = new AuthService();
export default authService;